import React from 'react';
import { Divider, Popconfirm, Icon, Input, Select, Table, Modal, Radio, Button, Form, Switch } from 'antd';
import { connect } from 'dva';
import Search from './search.js';
import styles from './index.less';

const { Option } = Select;
const namespace = 'role';
// import { connect } from 'dva';
/**
 *  用户管理中心
 */
@connect(({ role, loading }) => ({
  listData: role.listData,
  pagination: role.pagination,
  fieldData: role.fieldData,
  optionselect: role.optionselect,
  tableLoading: loading.effects['role/fetch']
}))
@Form.create()
class RolePage extends React.Component {
  state = {
    viewDialog: false,
    editDialog: false,
    isEdit: false,
    curItem: null, //当前选中得数据
    indeterminate: true,
    checkAll: false,
    visible: false, //弹窗
    plainOptions: [
      ['Dashboard view', 'Dashboard download', 'Finacial preview', 'Logistics dispatch'],
      ['Upload photo', 'Upload signature', 'Confirm pick-up window', 'Schedule appointmen'],
      ['Update warehosue location']
    ]
  };

  // 修改较色状态
  handleSWitch = (value, item) => {
    this.props.dispatch({
      type: `${namespace}/changeStatus`,
      payload: {
        ...item,
        status: value == 1 ? '0' : '1'
      }
    });
  };
  // 提交
  submitEditData = () => {
    const { curItem } = this.state;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.dispatch({
          type: `${namespace}/${curItem ? 'update' : 'add'}`,
          payload: {
            userId: this.props.listData.length,
            ...curItem,
            ...values
          }
        });
        this.setState({
          visible: false,
          curItem: null
        });
        this.props.form.resetFields();
      }
    });
  };

  // 关闭弹窗
  closeModal = () => {
    this.setState({
      visible: false,
      curItem: null
    });
  };
  //确认密码校验一致
  handleCfmPwd(rules, value, callback) {
    let password = this.props.form.getFieldValue('password');
    if (password && password !== value) {
      callback(new Error('The two passwords are inconsistent'));
    } else {
      callback();
    }
  }
  render() {
    const { listData, optionselect, tableLoading, pagination } = this.props;
    const { visible, curItem } = this.state;

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 13}
      }
    };
    const columns = [
      {
        title: 'Role',
        dataIndex: 'role',
        key: 'role'
      },
      {
        title: 'User name',
        dataIndex: 'userName',
        key: 'userName'
      },
      {
        title: 'Email',
        dataIndex: 'email',
        key: 'email'
      },
      {
        title: 'Create date',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: 'Status',
        dataIndex: 'status',
        key: 'status',
        render: (text, record) => (
          <div>
            <Switch
              onChange={checked => {
                this.props.dispatch({
                  type: `${namespace}/changeStatus`,
                  payload: {
                    ...record,
                    status: checked ? '0' : '1'
                  }
                });
              }}
              checked={text === '0' ? true : false}
            />
            <span style={{ marginLeft: '8px' }}>{text === '0' ? 'Active' : 'Inactive'}</span>
          </div>
        )
      },
      {
        title: 'Action',
        key: 'action',
        render: (text, record) => (
          <span>
            <Button
              onClick={() => {
                this.setState({
                  visible: true,
                  curItem: record
                });
                this.props.form.setFieldsValue({
                  role: record.role,
                  userName: record.userName,
                  status: record.status,
                  password: record.password,
                  email: record.email,
                  rawPassword: record.rawPassword
                });
              }}
              icon="edit"
            >
              Edit
            </Button>
            <Divider type="vertical" />
            <Popconfirm
              title="Are you sure you want to delete this warehouse？"
              okText="Yes"
              cancelText="No"
              onConfirm={() => {
                this.props.dispatch({
                  type: `${namespace}/delete`,
                  payload: {
                    id: record.userId
                  }
                });
              }}
              icon={<Icon type="question-circle-o" style={{ color: 'red' }} />}
            >
              <Button icon="delete">Delete</Button>
            </Popconfirm>
          </span>
        )
      }
    ];

    const paginationProps = {
      hideOnSinglePage: true,
      ...pagination,
      onShowSizeChange: current => {
        this.props.dispatch({
          type: `${namespace}/fetch`,
          payload: {
            pageNum: current
          }
        });
      },
      onChange: (page, pageSize) => {
        this.props.dispatch({
          type: `${namespace}/fetch`,
          payload: {
            pageNum: page,
            pageSize: pageSize
          }
        });
      }
    };
    const searchProps = {
      optionselect,
      handleSearch: params => {
        this.props.dispatch({
          type: `${namespace}/fetch`,
          payload: params
        });
      },
      showModal: () => {
        this.setState({
          visible: true
        });
      }
    };
    return (
      <div className={styles.rolePage}>
        <h2>Role management</h2>
        <Search {...searchProps} />
        <Table
          style={{ margin: '20px 0' }}
          columns={columns}
          loading={tableLoading}
          pagination={paginationProps}
          dataSource={listData}
        />

        <Modal
          title={curItem ? 'Eidt' : 'Add'}
          visible={visible}
          onOk={this.submitEditData}
          // destroyOnClose={true}
          onCancel={() => {
            this.setState({
              visible: false,
              curItem:null
            });
            this.props.form.resetFields();
          }}
        >
          <Form {...formItemLayout} onSubmit={this.handleSubmit}>
            <Form.Item label="Role">
              {getFieldDecorator('role', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your role!'
                  }
                ]
              })(
                <Select defaultValue="">
                  {optionselect &&
                    optionselect.map(item => {
                      return (
                        <Option key={item.remark} value={item.remark}>
                          {item.remark || ''}
                        </Option>
                      );
                    })}
                </Select>
              )}
            </Form.Item>
            <Form.Item label="User name">
              {getFieldDecorator('userName', {
                rules: [
                  {
                    required: true,
                    message: 'Please input your User name!'
                  }
                ]
              })(<Input />)}
            </Form.Item>
            <Form.Item label="Log in Email">
              {getFieldDecorator('email', {
                rules: [
                  {
                    type: 'email',
                    message: 'The input is not valid E-mail!'
                  },
                  {
                    required: true,
                    message: 'Please input your E-mail!'
                  }
                ]
              })(<Input />)}
            </Form.Item>
            {!curItem && (
              <div>
                <Form.Item label="Log in password">
                  {getFieldDecorator('password', {
                    rules: [
                      {
                        required: true,
                        message: 'Please input your password!'
                      }
                    ]
                  })(<Input type="password" />)}
                </Form.Item>
                <Form.Item label="Reconfirm password">
                  {getFieldDecorator('rawPassword', {
                    rules: [
                      { required: true, message: 'Please input your note!' },
                      {
                        validator: (rules, value, callback) => {
                          console.log(rules, value, 'callback', callback);
                          this.handleCfmPwd(rules, value, callback);
                        }
                      }
                    ],
                    validateFirst: true
                  })(<Input type="password" />)}
                </Form.Item>
              </div>
            )}

            <Form.Item label="Status">
              {getFieldDecorator('status', {
                initialValue: '1',
                rules: [
                  {
                    required: true,
                    message: 'Please input your status!'
                  }
                ]
              })(
                <Radio.Group>
                  <Radio value="0">Active</Radio>
                  <Radio value="1">Inactive</Radio>
                </Radio.Group>
              )}
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default RolePage;
